/**
 * Created by leiqr on 2015/5/21.
 * 渠道营销-全民经纪人-机构经纪人
 */
define(function (require, exports, module) {
    require("angular-ui");
    require("angular-route");
    var $ = require("jquery");
    var util = require("util");
    var ui = require("ui");
    var angular = require("angular");
    var dialogC = require("dialog");
    require("./imgpreview");

    var urlPrefix = window['G_CONFIG']['api_prefix'] + 'qmyx/broker/';

    angular.module('AgentBroker', ['ShowPreviewImg'])
        .factory('httpPost', ['$http', function ($http) {
            return function (url, data) {
                if (!data) {
                    data = {};
                }
                data = $.extend(data, {"USE_FORM_DATA": false});
                return $http.post(url, data);
            }
        }])
        .service('agentBrokerList', ['$q', 'httpPost', function ($q, httpPost) {
            return function (queryData) {
                var getParams = {
                    pageIndex: queryData.pageIndex,
                    pageSize: queryData.pageSize
                };
                var deferred = $q.defer();
                httpPost(urlPrefix + 'query-agency-broker-page-list&' + $.param(getParams), queryData)
                    .success(function (res) {
                        if (res.retCode == 0) {
                            deferred.resolve(res.data);
                        }
                    });
                return deferred.promise;
            }
        }])
        .service('brokerInfo', ['$q', '$http', function ($q, $http) {
            return function (id) {
                var deferred = $q.defer();
                $http.get(urlPrefix + 'get-broker-info-by-id&id=' + id)
                    .success(function (res) {
                        if (res.retCode == 0) {
                            deferred.resolve(res.data);
                        }
                    });
                return deferred.promise;
            }
        }])
        .controller('AgentController', ['$rootScope', '$scope', '$http', 'agentBrokerList', 'brokerInfo', 'httpPost',
            function ($rootScope, $scope, $http, agentBrokerList, brokerInfo, httpPost) {
                $scope.data = {};
                var dialogHandler, errorMessage = {};

                function showUploadTips(msg, callback) {
                    var fnClose = function () {
                        dialogHandler = null;
                        errorMessage = {};

                        if (callback) {
                            callback();
                        }
                    };

                    errorMessage[msg] = msg;
                    if (!dialogHandler) {
                        dialogHandler = dialogC({
                            title: '提示',
                            fixed: true,
                            content: msg + '',
                            width: 350,
                            okValue: '确定',
                            cancelDisplay: false,
                            ok: fnClose,
                            cancel: fnClose
                        }).showModal();
                    } else {
                        //var margeMsg = _.keys(errorMessage).join('<br /><br />');//提示会累积
                        var margeMsg = msg;
                        dialogHandler.content(margeMsg);
                        dialogHandler.reset();
                    }
                }

                $scope.approvalTabs = [
                    {
                        name: '未审定',
                        value: [0],
                        audited: false
                    },
                    {
                        name: '已审定',
                        value: [1],
                        audited: true
                    }];
                $scope.disableFilters = [
                    {
                        text: '已禁用',
                        value: 1
                    },
                    {
                        text: '未禁用',
                        value: 0
                    }
                ];
                $scope.currentState = $scope.initAudited ? $scope.approvalTabs[1] : $scope.approvalTabs[0];
                $scope.setApprovalState = function (tab) {
                    $scope.currentState = tab;
                    $scope.clearFilter();
                    $scope.pageIndex = 1;
                    delete $scope.filter.disabled_arr;
                    $scope.filter.status_arr = tab.value;
                    $scope.getList(-1);
                };

                /**
                 * 选中经纪人身份
                 * @param agency
                 */
                $scope.setAgencySelected = function (event, agency) {
                    clearAgencySelected();
                    $scope.curAgency = agency;
                    $scope.agencyItems = agency.items;
                    $scope.filter.agency_arr = [$scope.curAgency.value];
                    if (event) {
                        ui.changeTipsArrow(event.currentTarget);
                    }
                };

                $scope.data.agencySelectedAll = false;
                $scope.changeAgencyAll = function () {
                    var agencyItems = $scope.agencyItems;
                    var agencySelectedAll = $scope.data.agencySelectedAll;
                    var item;
                    for (var i = 0; item = agencyItems[i]; i++) {
                        item.selected = agencySelectedAll;
                    }
                    updateAgencySelected();
                };
                $scope.changeAgency = function (agency) {
                    var selected = true;
                    var item;
                    for (var i = 0; item = $scope.agencyItems[i]; i++) {
                        if (!item.selected) {
                            selected = false;
                            break;
                        }
                    }
                    $scope.data.agencySelectedAll = selected;
                    updateAgencySelected();
                };
                function clearAgencySelected() {
                    $scope.data.agencySelectedAll = false;
                    var agencyItems = $scope.agencyItems;
                    if (agencyItems) {
                        var item;
                        for (var i = 0; item = agencyItems[i]; i++) {
                            item.selected = false;
                        }
                    }
                }

                function updateAgencySelected() {
                    var agencyArr = [];
                    var agencyItems = $scope.agencyItems;
                    if (agencyItems) {
                        var item;
                        for (var i = 0; item = agencyItems[i]; i++) {
                            if (item.selected) {
                                agencyArr.push(item.value);
                            }
                        }
                    }
                    $scope.filter.agency_arr = agencyArr;
                }

                /**
                 * 城市选中状态变化
                 * @param city
                 */
                $scope.changeCitySelected = function (city) {
                    var cityIdArr = [];

                    var cities = $scope.cities;
                    var item;
                    for (var i = 0; item = cities[i]; i++) {
                        if (item.selected) {
                            cityIdArr.push(item.value);
                        }
                    }

                    $scope.filter.city_id_arr = cityIdArr;
                };

                /**
                 * 禁用状态勾选
                 * @param item
                 */
                $scope.setDisableFilters = function (item) {
                    var disabled_arr = [];
                    var disableFilters = $scope.disableFilters;
                    var item;
                    for (var i = 0; item = disableFilters[i]; i++) {
                        if (item.selected) {
                            disabled_arr.push(item.value);
                        }
                    }
                    $scope.filter.disabled_arr = disabled_arr;
                };
                /**
                 * 清理勾选
                 */
                $scope.clearFilterStatus = function () {
                    /**
                     * 清理城市选中
                     */
                    var cities = $scope.cities;
                    if (typeof cities === 'undefined') {
                        return;
                    }
                    var item;
                    for (var i = 0; item = cities[i]; i++) {
                        item.selected = false;
                    }
                    //未审定没有审核状态和禁用状态
                    if (!$scope.currentState.audited)return;
                    /**
                     * 清理禁用状态选中
                     */
                    var disableFilters = $scope.disableFilters;
                    for (var i = 0; item = disableFilters[i]; i++) {
                        item.selected = false;
                    }
                };

                /**
                 * 清理筛选条件
                 */
                $scope.clearFilter = function () {
                    $scope.filter.agency_arr = [];
                    $scope.filter.search_text = '';
                    $scope.curAgency = null;
                    $scope.data.agencySelectedAll = false;
                    clearAgencySelected();
                    $scope.agencyItems = [];
                    $scope.filter.agency_arr = [];

                    $scope.clearFilterStatus();
                    $scope.filter.city_id_arr = [];
                    $scope.filter.status_arr = $scope.currentState.value;
                    $scope.filter.disabled_arr = [];

                    $scope.filter.begin_reg_date = null;
                    $scope.filter.end_reg_date = null;
                    $scope.getList(1);
                };

                //检查是否需要另开页面下载
                $scope.beforeExportData = function(params){
                    var taskId = false;
                    $.ajax({
                        type: 'POST',
                        async:false,
                        data:JSON.stringify(params),
                        contentType:'application/json;charset=UTF-8',
                        url: urlPrefix + "check-export-agency-broker-need-task&token="+util.getToken(),
                        success: function(re) {
                            if(re.data.needTask){
                                taskId = re.data.taskId;
                            }
                        },
                        error:function(){

                        }
                    });
                    return taskId;
                };

                /**
                 * 导出数据
                 */
                $scope.exportData = function () {

                    var params = getQueryData();
                    var task = $scope.beforeExportData(params);
                    if(!task){
                        util.download(urlPrefix + 'export-agency-broker', {filter: JSON.stringify(params)});
                    }else{
                        window.open('/page/export_data.shtml?taskId='+task);
                    }

                };
                $scope.filter = {
                    pageIndex: 0,
                    pageSize: 10,
                    search_text: "",
                    search_field: "",
                    agency_arr: [],
                    city_id_arr: [],
                    begin_reg_date: null,
                    end_reg_date: null,
                    status_arr: $scope.currentState.value
                };
                if ($scope.currentState.audited) {
                    $scope.filter.disabled_arr = [];
                }

                /**
                 * 翻页
                 * @param {int} pageIndex
                 */
                $scope.getDataPage = function (pageIndex) {
                    $scope.filter.pageIndex = pageIndex - 1;
                    $scope.getList();
                };

                /**
                 * 审核
                 * @param {Object} item
                 * @param {int} status
                 */
                $scope.setStatus = function (item, status) {
                    var method = status == 1 ? 'audit-pass' : 'audit-fail';
                    return $http.post(urlPrefix + method, {brokerIds: item.broker_id})
                        .success(function (res) {
                            if (res.retCode == 0) {
                                $scope.getList().finally(function () {
                                    ui.showSucTip();
                                })
                            }
                        })
                };

                /**
                 * 批量审核
                 * @param {int} status
                 */
                $scope.setSelectedBrokersStatus = function (status) {
                    var ids = [];

                    var list = $scope.list;
                    if (list) {
                        var item;
                        for (var i = 0; item = list[i]; i++) {
                            if (item.selected) {
                                ids.push(item.broker_id);
                            }
                        }
                    }

                    if (ids.length > 0) {
                        var method = status == 1 ? 'audit-pass' : 'audit-fail';
                        httpPost(urlPrefix + method, {brokerIds: ids.join()})
                            .success(function (res) {
                                if (res.retCode == 0) {
                                    $scope.getList().finally(function () {
                                        ui.showSucTip();
                                    })
                                }
                            })
                    }
                };

                /**
                 * 展示经纪人详情
                 * @param {Object} item
                 * @param dialog
                 * @param dialogScope
                 */
                $scope.onShowBrokerInfo = function (item, dialog, dialogScope) {
                    dialog.button([]);
                    dialogScope.handleBroker = $scope.handleBroker;

                    dialogScope.showPreviewImg = function (src) {
                        var imgpreview;
                        $scope.ImgSize(src, function () {
                            var w = this.width, h = this.height;
                            var maxW = 1100, minW = 250;
                            if (w > maxW) {
                                w = maxW;
                                h = maxW / w * h;
                            } else if (w > minW) {
                                w = minW;
                                h = minW / w * h;
                            }
                            imgpreview = dialogC({
                                title: '图片预览',
                                fixed: true,
                                content: '<img width="100%" height="100%" src="' + src + '" />',
                                width: w,
                                height: h,
                                okDisplay: false,
                                cancelDisplay: false
                            }).showModal();
                        });
                    };

                    dialogScope.deleteBroker = function () {
                        $scope.deleteBroker.apply($scope, arguments)
                            .success(function (res) {
                                if (res.retCode == 0) {
                                    dialog.close();
                                }
                            })
                    }
                    dialogScope.currentState = $scope.currentState;
                    dialogScope.setStatus = function (data, status) {
                        $scope.setStatus.apply($scope, arguments).success(function (res) {
                            dialogScope.data.status = status;
                            if (status == 1) {
                                dialogScope.data.status_info = '已通过';
                            } else if (status == 2) {
                                dialogScope.data.status_info = '未通过';
                            } else {
                                dialogScope.data.status_info = '未审核';
                            }
                            dialog.close();
                        })
                    };
                    dialogScope.setInvite = $scope.setInvite;
                    brokerInfo(item.broker_id)
                        .then(function (info) {
                            dialogScope.data = info;
                        })
                        .finally(function () {
                            setTimeout(function () {
                                dialog.reset();
                            }, 0);
                        })
                };
                $scope.onShowBatchTips = function (item, dialog, dialogscope) {
                    var ids = [];

                    var list = $scope.list;
                    if (list) {
                        var item;
                        for (var i = 0; item = list[i]; i++) {
                            if (item.selected) {
                                ids.push(item.broker_id);
                            }
                        }
                    }

                    if (ids.length > 0) {
                        return true;
                    }else{
                        showUploadTips('请选择要操作的记录！')
                    }
                    return false;

                };
                $scope.filename = 'filename';
                /**
                 *启用、禁用、删除
                 *
                 */
                $scope.handleBroker = function (item, opt) {
                    var map = {'disable': 'disable-broker', 'enable': 'enable-broker', 'del': 'delete-broker'};
                    if (opt && _.has(map, opt)) {
                        var method = map[opt];
                    } else {
                        return;
                    }
                    return $http.post(urlPrefix + method + '&id=' + item.broker_id)
                        .success(function (res) {
                            if (res.retCode == 0) {
                                $scope.getList().finally(function () {
                                    ui.showSucTip();
                                    if (opt == 'disable' || opt == 'enable') {
                                        item.isdisabled = !item.isdisabled;
                                    }
                                })
                            }
                        })
                };
                $scope.deleteBroker = function (data, opt, dialog, dialogScope) {
                    return $scope.handleBroker(data, opt);
                };
                /**
                 *更新经纪人是否允许邀请
                 *
                 */
                $scope.setInvite = function (item, opt) {
                    var canInvite = true;
                    if (typeof opt !== 'undefined') {
                        canInvite = opt;
                    } else {
                        return;
                    }
                    $http.post(urlPrefix + 'update-can-invite-broker&id=' + item.broker_id + '&canInvite=' + canInvite)
                        .success(function (res) {
                            if (res.retCode == 0) {
                                $scope.getList().finally(function () {
                                    ui.showSucTip();
                                    item.can_invite_broker = !item.can_invite_broker;
                                })
                            }
                        })
                };
                /**
                 * 编辑经纪人详情
                 * @param {Object} item
                 * @param dialog
                 * @param dialogScope
                 */
                $scope.onShowEditBrokerInfo = function (item, dialog, dialogScope) {
                    dialogScope.agencies = $scope.agencies;
                    brokerInfo(item.broker_id)
                        .then(function (info) {
                            dialogScope.data = info;
                        })
                        .finally(function () {
                            setTimeout(function () {
                                dialog.reset();
                            }, 0);
                        })
                };
                /**
                 * 重设密码对话框
                 * @param {Object} item
                 * @param dialog
                 * @param dialogScope
                 */
                $scope.onShowChangePwd = function (item, dialog, dialogScope) {
                    dialogScope.data = item;
                };
                /**
                 * 重设密码
                 * @param {Object} data
                 */
                $scope.changePwd = function (data) {
                    $http.post(urlPrefix + 'reset-broker-password&id=' + data.broker_id +
                        '&password1=' + data.password1 + '&password2=' + data.password2)
                        .success(function (res) {
                            if (res.retCode == 0) {
                                $scope.getList().finally(function () {
                                    ui.showSucTip();
                                })
                            }
                        })

                };
                /**
                 * 更新经纪人身份
                 * @param {Object} data
                 */
                $scope.saveBrokerInfo = function (data) {
                    $http.post(urlPrefix + 'update-broker-agency&id=' + data.broker_id +
                        '&agencyDes=' + data.agency_des + '&belongsCompany=' + data.belongs_company)
                        .success(function (res) {
                            if (res.retCode == 0) {
                                $scope.getList().finally(function () {
                                    ui.showSucTip();
                                })
                            }
                        })

                };
                $scope.data.selectedAllBrokers = false;
                /**
                 * 改变经纪人全选状态
                 */
                $scope.changeSelectedAllBrokers = function () {
                    if ($scope.list) {
                        var item;
                        for (var i = 0; item = $scope.list[i]; i++) {
                            item.selected = $scope.data.selectedAllBrokers;
                        }
                    }
                };


                /**
                 * 查询状态
                 * @type {number}
                 */
                $scope.searchStatus = $scope.initAgentId ? $scope.searchStatus : -1;

                /**
                 * @param {int=} searchStatus
                 * @returns {{}}
                 */
                function getQueryData(searchStatus) {
                    if (searchStatus == 1 || 0 == searchStatus) {
                        $scope.filter.pageIndex = 0;
                        $scope.pageIndex = 1;
                    }
                    var queryData = $scope.filter;

                    if (typeof searchStatus !== 'undefined') {
                        $scope.searchStatus = searchStatus;
                    } else {
                        searchStatus = $scope.searchStatus;
                    }

                    var keys;

                    switch (searchStatus) {
                        case -2:
                            keys = [
                                'pageIndex',
                                'pageSize',
                                'status_arr',
                                'agency_arr'
                            ];
                            break;
                        case -1:
                            keys = [
                                'pageIndex',
                                'pageSize',
                                'status_arr'
                            ];
                            break;
                        case 0:
                            keys = [
                                'pageIndex',
                                'pageSize',
                                'search_text',
                                'search_field',
                                'status_arr'
                            ];
                            break;
                        case 1:
                            keys = [
                                'pageIndex',
                                'pageSize',
                                'agency_arr',
                                'city_id_arr',
                                'begin_reg_date',
                                'end_reg_date',
                                'status_arr',
                                'disabled_arr'
                            ];
                            break;
                        default :
                            keys = [
                                'pageIndex',
                                'pageSize',
                                'status_arr'
                            ];
                    }

                    var filterData = {};

                    var key;
                    for (var i = 0; key = keys[i]; i++) {
                        if (queryData.hasOwnProperty(key)) {
                            filterData[key] = queryData[key];
                        }
                    }

                    return filterData;
                }

                /**
                 * @param {int=} searchStatus
                 */
                $scope.getList = function (searchStatus) {
                    var filterData = getQueryData(searchStatus);
                    return agentBrokerList(filterData)
                        .then(function (data) {
                            $scope.list = data.items;
                            $scope.total = data.total;
                            $scope.pageIndex = $scope.filter.pageIndex + 1;
                        })
                        .finally(function () {
                            $scope.data.selectedAllBrokers = false;
                        })
                };

                //获取查询数据
                $http.get(urlPrefix + 'get-agency-broker-filter-setting')
                    .success(function (res) {
                        if (res.retCode == 0) {
                            var data = res.data;
                            var searchFields = [];

                            var searchFields2 = data.searchFields;
                            for (var key in  searchFields2) {
                                if (searchFields2.hasOwnProperty(key)) {
                                    searchFields.push({
                                        value: key,
                                        name: searchFields2[key]
                                    })
                                }
                            }

                            $scope.searchFields = searchFields;
                            $scope.filter.search_field = searchFields[0].value;

                            $scope.agencies = data.agencies;
                            $scope.cities = data.cities;
                            if ($scope.initAgentId) {
                                var _cur = _.find($scope.agencies, function (v) {
                                    return v.value == $scope.initAgentId;
                                })
                                if (_cur) {
                                    $scope.curAgency = _cur;
                                    $scope.agencyItems = _cur.items;
                                    $scope.filter.agency_arr = [_cur.value];
                                }
                            }

                        }
                    });
                if ($scope.initAgentId) {
                    $scope.filter.agency_arr = [$scope.initAgentId];
                }
                $scope.getList();

            }
        ])
});
